<template>
  <div>
    <el-dialog :title="option.title" :visible.sync="isShow" :close-on-click-modal="false" width="60%" @open="openDialog" @close="closeDialog">
      <el-card>
        <el-form>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附属机构号">
              <el-checkbox-group 
                v-model="AUX_BRNO"
                :min="0"
                :max="1"
                v-if="AUX_BRNOS.length!=0">
                <el-checkbox v-for="(item,index) in AUX_BRNOS" 
                  :key="index" 
                  :label="item.value" border
                  style="float: left;">{{item.label}}</el-checkbox>
              </el-checkbox-group>
              <span v-else>暂无数据</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button type="primary" size="small" @click="queryClick" :disabled="AUX_BRNO.length != 1">查询</el-button>
            <el-button type="primary" size="small" @click="openPop" :disabled="AUX_BRNO.length != 1">新增</el-button>
            <el-button type="primary" size="small" @click="submitForm()" :disabled="this.tableData.length == 0 ">保存</el-button>
          </el-col>
        </el-row>
        </el-form>
        <div v-show="option.op==='3'">
          <el-table border style="width: 100%;margin-top:20px;" ref="multipleTable" 
            :data="tableData"
            v-if="option.op==='3'"
            @selection-change="changeFun"
            @select="selectMemoryFn"
            @select-all="selectAll">
            <!-- <el-table-column type="selection" width="55" :selectable='checkboxInit' align="center"></el-table-column> -->
            <el-table-column prop="WORKMODEID" align="center" width="120">
              <template slot="header" slot-scope="scope">
                <span class="myStar">*</span>
                工作模式编号
              </template>
            </el-table-column>
            <el-table-column prop="WORKMODENAME" align="center" width="120">
              <template slot="header" slot-scope="scope">
                <span class="myStar">*</span>
                工作模式名称
              </template>
            </el-table-column>
            <el-table-column prop="NOTES" label="说明" align="center" width="120"></el-table-column>
            <el-table-column prop="SRTDATE" width='340' align="center">
              <template slot="header" slot-scope="scope">
                <span class="myStar">*</span>
                开始时间-结束时间
              </template>
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.SRTDATE"
                  type="daterange"
                  range-separator="-"
                  unlink-panels
                  size="small"
                  value-format="yyyyMMdd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button type="text" @click="delClick('4',scope.row)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-show="option.op==='4'">
          <el-table border style="width: 100%;margin-top:20px;" ref="multipleTable" 
            :data="tableData"
            @selection-change="changeFun"
            @select="selectMemoryFn"
            @select-all="selectAll">
            <!-- <el-table-column type="selection" width="55" :selectable='checkboxInit' align="center"></el-table-column> -->
            <el-table-column prop="ASSIGNRULEID" label="分配规则编号" align="center"></el-table-column>
            <el-table-column prop="ASSIGNRULENAME" label="分配规则名称" align="center"></el-table-column>
            <el-table-column prop="SRTDATE" label="开始时间-结束时间" width='340' align="center">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.SRTDATE"
                  type="daterange"
                  range-separator="-"
                  unlink-panels
                  size="small"
                  value-format="yyyyMMdd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button type="text" @click="delClick('4',scope.row)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div style="text-align:right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage" 
            :page-sizes="[5]"  
            :page-size="pageSize" 
            layout="prev, pager, next" 
            :total="tableTotal">
          </el-pagination>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="option.isShow = false;" size="mini">取 消</el-button>
        <!-- <el-button type="primary" @click="saveModel()" size="mini">确 定</el-button> -->
      </div>
    </el-dialog>

    <component :is="dialogList.tableDialog" :option="editOptions"></component>
  </div>
</template>

<script>
import request from "@/common/utils/requestWFM";
import getGlobalParams from "@/common/utils/getGlobalParams";
import Query from '@/message/wfm/scheduleDataManage/workModel/workQuery';
import assignQuery from '@/message/wfm/scheduleDataManage/assignRules/assignQuery';
import extraBranchQuery from '@/message/seat-manage/extraBranch/branchQuery';
import tableDialog from './tableDialog.vue';

export default {
  props: { option: Object },
  data() {
    return {
      dialogList: { tableDialog },
      editOptions:{
        isShow:false,
        title: '',
        BRANCHNO: ''
      },
      tableData: [],
      tableTotal: 1,
      currentPage: 1,
      pageSize: getGlobalParams.get("PageSize"),
      multipleSelection: [], // 选中的数据二维数组
      WORKMODEID: [], // 选中的数据WORKMODEID数组
      ASSIGNRULEID: [],// 选中的数据ASSIGNRULEID数组
      checkList: [], //选中数列
      rowData: [],
      transmitData: [], //需要入参数据
      // 附属机构号
      AUX_BRNO: [],
      AUX_BRNOS: [],
    }
  },
  computed: {
    isShow: {
      get() {
        return this.option.isShow;
      },
      set(value) {
        this.option.isShow = value;
      }
    },
  },
  watch: {
    'tableData.WORKMODEID':function (oldVal, newVal) { // 监听数据变化，然后执行分页记忆自动选中回调
      this.$nextTick(() => {
        this.selectMemoriedDataFn();
      })
    },
    'tableData.ASSIGNRULEID':function (oldVal, newVal) { // 监听数据变化，然后执行分页记忆自动选中回调
      this.$nextTick(() => {
        this.selectMemoriedDataFn();
      })
    },
  },
  mounted(){

  },
  methods: {
    closeDialog(){
      this.AUX_BRNO = [];
      this.AUX_BRNOS = [];
      this.tableData = [];
      this.tableTotal = 1;
      this.currentPage = 1;
      this.multipleSelection = [];
      this.WORKMODEID = [];
      this.ASSIGNRULEID = [];
      this.checkList = [];
      this.rowData = [];
      this.transmitData = [];
    },
    openDialog() {
      this.openExtraBranch();
      this.checkList =[];
      // if(this.option.op === '3'){
      //   this.queryWorkModel();
      // }else if(this.option.op === '4'){
      //   this.queryAssignRules();
      // }else{
      //   alert('error');
      // }
      this.transmitData = this.rowData = JSON.parse(JSON.stringify(this.option.row)); 
      var list = [];
      this.rowData.forEach(item=>{
        list.push(this.option.op === '3'?item.WORKMODEID:item.ASSIGNRULEID);
      })
      this.checkList = list?list:[];
    },
    //前端分页
    handleSizeChange(val) {
      this.pageSize = val;
       if(this.option.op === '3'){
        this.queryWorkModel();
      }else if(this.option.op === '4'){
        this.queryAssignRules();
      }else{
        alert('error');
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
       if(this.option.op === '3'){
        this.queryWorkModel();
      }else if(this.option.op === '4'){
        this.queryAssignRules();
      }else{
        alert('error');
      }
    },
    // 工作模式查询
    async queryWorkModel() {
      let resBody = new Query()
      resBody.data.BRANCHNO = this.option.BRANCHNO;
      resBody.data.WORKMODEID = '';
      resBody.data.WORKMODENAME = '';
      resBody.data.CurrPage = this.currentPage;
      resBody.data.PageRowNum = this.pageSize;
      let response = await request(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.tableTotal = response.BODY.TotalRowNum;
        this.tableData = response.BODY.RSPSTRUCT;
        // 已选中得不可更改时间
        this.tableData.forEach(item=>{
          if (this.checkList.indexOf(item.WORKMODEID)!=-1){
            item.disabled = true;
          }else{
            item.disabled = false;
          } 
        })
      } else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        })
      }
    },
    // 分配规则查询
    async queryAssignRules() {
      let resBody = new assignQuery();
      resBody.data.BRANCHNO = this.option.BRANCHNO;
      resBody.data.ASSIGNRULEID = '';
      resBody.data.ASSIGNRULENAME = '';
      resBody.data.CurrPage = this.currentPage;
      resBody.data.PageRowNum = this.pageSize;
      let response = await request(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.tableTotal = response.BODY.TotalRowNum;
        this.tableData = response.BODY.ASSIGNRULE;
        // 已选中得不可更改时间
        this.tableData.forEach(item=>{
          if (this.checkList.indexOf(item.ASSIGNRULEID)!=-1){
            item.disabled = true;
          }else{
            item.disabled = false;
          } 
        })
      } else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        })
      }
    },
    checkboxInit(row,index){
      if(this.option.op==='3'){
        if (this.checkList.indexOf(row.WORKMODEID)!=-1){
          return false;//不可勾选
        }else{
          return true;//可勾选
        } 
      }else{
        if (this.checkList.indexOf(row.ASSIGNRULEID)!=-1){
          return false;//不可勾选
        }else{
          return true;//可勾选
        } 
      } 
    },
    changeFun(val) {
      if(this.option.op === '3'){
        this.$nextTick(() => {
          let WORKMODEID = []
          this.multipleSelection.forEach(L => L.forEach(M => WORKMODEID.push(M.WORKMODEID)))
          this.WORKMODEID = WORKMODEID;
        })
      }else{
        this.$nextTick(() => {
          let ASSIGNRULEID = []
          this.multipleSelection.forEach(L => L.forEach(M => ASSIGNRULEID.push(M.ASSIGNRULEID)))
          this.ASSIGNRULEID = ASSIGNRULEID;
        })
      }
      
    },
    selectAll (selection) { // 全选切换方法
      if (selection.length) { // 全选
        this.multipleSelection[this.currentPage-1] = selection
      } else { // 全不选
        this.multipleSelection[this.currentPage-1] = []
      }
    },
    selectMemoryFn (val, row) { // 设置分页记忆二位数组方法
      // 注意：val 传过来默认为数组类型 ，row 为 Object（当前选择数据对象）
      let currentArr = this.multipleSelection[this.currentPage-1] // 当前分页对应数组
      if (!currentArr) {
        this.multipleSelection[this.currentPage-1] = val // 不存在这个二维数组，则创建这个二位数组
      } else { // 存在
        if (val.includes(row)) { // 选中
          this.multipleSelection[this.currentPage-1] = val
        } else { // 取消
          for(var i=0;i<currentArr.length;i++){
            if(currentArr[i]){
              if(this.option.op === '3'){
                if(currentArr[i].WORKMODEID == row.WORKMODEID){
                  delete currentArr[i];
                  break;
                }
              }else{
                if(currentArr[i].ASSIGNRULEID == row.ASSIGNRULEID){
                  delete currentArr[i];
                  break;
                }
              }
            }
          }
        }
      }
    },
    selectMemoriedDataFn () { // 分页记忆自动选中方法
      if(this.option.op === '3'){
        let currentArr = this.multipleSelection[this.currentPage-1]  // 当前分页对应被选中数据
        if (currentArr && currentArr.length) { // 存在则继续执行
          let tempRowsIDs = this.tableData.map(L => L.WORKMODEID) // 当前分页被选中数据的id集合
          currentArr.forEach((item, index) => { // 遍历当前分页被选中数据
            if (tempRowsIDs.includes(item.WORKMODEID)) { // id匹配上，则选中
              this.$refs.multipleTable.toggleRowSelection(this.tableData[tempRowsIDs.indexOf(item.WORKMODEID)])
            }
          })
        }
      }else{
        let currentArr = this.multipleSelection[this.currentPage-1]  // 当前分页对应被选中数据
        if (currentArr && currentArr.length) { // 存在则继续执行
          let tempRowsIDs = this.tableData.map(L => L.ASSIGNRULEID) // 当前分页被选中数据的id集合
          currentArr.forEach((item, index) => { // 遍历当前分页被选中数据
            if (tempRowsIDs.includes(item.ASSIGNRULEID)) { // id匹配上，则选中
              this.$refs.multipleTable.toggleRowSelection(this.tableData[tempRowsIDs.indexOf(item.ASSIGNRULEID)])
            }
          })
        }
      } 
    },
    // saveModel() {
    //   var re = false;
    //   var transmitData = [];
    //   if(this.multipleSelection.length > 0){
    //     this.multipleSelection.forEach(item=>{
    //       transmitData = [];
    //       item.forEach((info,i)=>{
    //         if(info.SRTDATE == undefined || info.SRTDATE.length == 0 ){
    //           re = true;
    //           return;
    //         }else{
    //           if(this.option.op === '3'){
    //             transmitData.push({
    //               'WORKMODEID':info.WORKMODEID,
    //               'WORKMODENAME':info.WORKMODENAME,
    //               'SRTDATE':[info.SRTDATE[0],info.SRTDATE[1]],
    //             });
    //           }else{
    //             transmitData.push({
    //               'ASSIGNRULEID':info.ASSIGNRULEID,
    //               'ASSIGNRULENAME':info.ASSIGNRULENAME,
    //               'SRTDATE':[info.SRTDATE[0],info.SRTDATE[1]],
    //             });
    //           }
    //         }
    //       })
    //     })
    //     if(re){
    //       this.$message({
    //         type: "error",
    //         message: "请选择时间"
    //       })
    //       return ;
    //     }
    //     transmitData.forEach(item=>{
    //       this.transmitData.push(item);
    //     })
    //     this.$parent.$parent.editUserBaseData(this.option.op,this.transmitData);
    //     this.option.isShow = false;
    //   }else{
    //     this.option.isShow = false;
    //   }
    // },
    // 从父组件查询出的数据
    childAction(val){
      this.tableData = val;
    },
    queryClick(){
      this.$parent.queryModel(this.AUX_BRNO[0],this.option.op);
    },
    // 坐席附属机构/班查询
    async openExtraBranch() {
      let resBody = new extraBranchQuery();
      resBody.data.AGENTID = this.$parent.checkedCities[0];
      let response = await request(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.AUX_BRNOS = [];
        var obj = response.BODY.AUXDATA[0];
        if(response.BODY.AUXDATA.length > 0){
          if(obj.AUX_BRNO1){
            this.AUX_BRNOS.push({
              "label":obj.AUX_BRNAME1,
              "value":obj.AUX_BRNO1,
            })
          }
          if(obj.AUX_BRNO2){
            this.AUX_BRNOS.push({
              "label":obj.AUX_BRNAME2,
              "value":obj.AUX_BRNO2,
            })
          }
          if(obj.AUX_BRNO3){
            this.AUX_BRNOS.push({
              "label":obj.AUX_BRNAME3,
              "value":obj.AUX_BRNO3,
            })
          }
        }
      } else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        })
      }
    },
    submitForm(op,data){
      if(op){
        this.$parent.editUserBaseData(op,data);
      }else{
        this.$parent.editUserBaseData(this.option.op,this.tableData);
      }
      // console.log(this.tableData,this.option.op);
    },
    openPop() {
      var data = [];
      var title = '';
      if(this.option.op == '3'){
        data = this.tableData||[];
        title = '增加附属机构工作模式列表';
      }else if(this.option.op == '4'){
        data = this.tableData||[];
        title = '增加附属机构分配规则列表';
      }else{
        console.log('error');
      }
      this.editOptions.isShow = true;
      this.editOptions.title = title;
      this.editOptions.row = data;
      this.editOptions.op = this.option.op;
      this.editOptions.BRANCHNO = this.AUX_BRNO[0];
      this.editOptions.parent = 'auxBrn';
    },
    delClick(op,row){
      this.$parent.delClick(op,row,'ddd');
    }
  }
};
</script>

<style  scoped lang="scss">
.el-date-editor{
  width: 100%;
}
.myStar{
  color: #F56C6C;
  margin-right: 4px;
}
.el-checkbox-group {
  padding: 0 10px 10px;
}

.el-checkbox:first-child {
  margin-left: 10px;
}

.el-checkbox {
  display: inline-block;
  margin-bottom: 10px;
  width: 135px;
  display: flex;
  height: auto;
  padding: 6px 15px 6px 10px;
  white-space: inherit;
}
</style>
